import axios from "axios"
import { ElMessage } from 'element-plus'

const request = axios.create({
    baseURL: "http://mall.itanychw.online:8888/api/v2/"
    // baseURL:"http://www.tangxiaoyang.vip:8888/api/v2/"
});

const ERROR_MSG={
    ERR_NETWORK:"网络异常，请检查网络连接",
    ECONNABORTED:"请求超时,请稍后重试"
};
const HTTP_MSG={
    401:"未授权",
    404:"访问资源不存在",
    500:"服务器出现异常",
    DEFAULT:"服务器太忙了,你待会再试"
}

request.interceptors.request.use(
    function(config){
        // console.log(config)
        config.headers.Authorization = sessionStorage.getItem("token")
        return config;
    },
    function(error){
        return Promise.reject(error);
    }
)
request.interceptors.response.use(
    function(response){
        if(response.data.meta.status>=400){
            // 业务失败
            ElMessage.error( response.data.meta.msg );
            return null;
        }else{
            // 业务成功 - 只返回后台响应的数据，不返回业务状态
            return response.data.data
        }
    },
    function(error){
        let msg="";
        if(error.response){
            msg= HTTP_MSG[error.response.status];
        }else{
            msg=ERROR_MSG[error.code]
        }
        ElMessage.error(msg)
        return Promise.reject(msg)
    }
)

export default request;